<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="lib/protobuf/protobuf.min.js"></script>
</head>
<body>
<div>
    在控制台中查看交互结果
</div>
</body>
<script>
    protobuf.load("HeartBeat.proto")
        .then(function (root) {
            // Obtain a message type
            var HeartBeat = root.lookupType("HeartBeat");
            var payload = {heart: 10, time: 20, ids: 131, requestInfo: 400};
            var message = HeartBeat.create(payload);
            var buffer = HeartBeat.encode(message).finish();
            console.log(buffer);

            // 只能使用XMLHttpRequest与后台交互
            var getXhr = new XMLHttpRequest();
            getXhr.responseType = "arraybuffer";
            getXhr.onreadystatechange = function() {
                if (getXhr.readyState === 4) {
                    console.log(getXhr.response);
                    console.log(new Uint8Array(getXhr.response));
                    var msg = HeartBeat.decode(new Uint8Array(getXhr.response));
                    var obj = HeartBeat.toObject(msg, {
                        enums: String,  // enums as string names
                        longs: String,  // longs as strings (requires long.js)
                        bytes: String,  // bytes as base64 encoded strings
                        defaults: true, // includes default values
                        arrays: true,   // populates empty arrays (repeated fields) even if defaults=false
                        objects: true,  // populates empty objects (map fields) even if defaults=false
                        oneofs: true    // includes virtual oneof fields set to the present field's name
                    });
                    console.log(obj);
                }
            };
            getXhr.open("GET", "/protobuf/", true);
            getXhr.send(null);


            var postXhr = new XMLHttpRequest();
            postXhr.open("POST", "/protobuf/", false);
            postXhr.setRequestHeader("Content-type", "application/x-protobuf");
            postXhr.send(buffer);
            var postDoc = postXhr.responseText;
            console.log(postDoc);
        });
</script>
</html>